# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
from odoo.exceptions import ValidationError, Warning
import datetime
from lxml import etree

# 维保公司的维保星级
AVILABLE_MAINTENNANCE_STARS = [
    ('-1', '没有星级'),
    ('0', '一星级'),
    ('1', '二星级'),
    ('2', '三星级'),
    ('3', '四星级'),
    ('4', '五星级'),
]

# 救援人员角色
MAINTENANCE_SALVAGER_ROLES = [
    ('head_of_unit', '公司负责人'),
    ('first_salvager', '第一救援负责人'),
    ('second_salvager', '第二救援负责人'),
    ('third_salvager', '第三救援负责人'),
]

# 使用单位救援人员角色
USE_COMPANY_SALVAGER_ROLES = [
    ('use_company_manager', '电梯安全管理员'),
    ('lift_manager', '电梯作业人员')
]

QS_LEVEL = [
    ('1', '市局'),
    ('2', '区/县局'),
    ('3', '所')
]

QS_POSITION = [
    ('director_general', '局长'),
    ('deputy_director_general', '分管副局长'),
    ('unit_chief', '股长'),
]


class QSCompany(models.Model):
    """
    质监单位
    """
    _name = "tyibs.base.qs.company"

    @api.depends("employee_ids", "child_ids")
    def _compute_count(self):
        for item in self:
            item.employee_count = len(item.employee_ids)
            item.child_ids_count = len(item.child_ids)

    name = fields.Char(string=u"单位名称", required=True, index=True, search=True) 
    level = fields.Selection(QS_LEVEL, string=u"层级类型")

    # 联系信息
    contact = fields.Char(string=u"负责人", required=True )
    phone = fields.Char(string=u"固定电话")
    mobile = fields.Char(string=u"手机号码", required=True)
    email = fields.Char(string=u"电子邮件")

    # 法人
    legal_person = fields.Char(string=u"法人")
    legal_person_mobile = fields.Char(string=u"法人手机")

    # 单位负责人
    manager_person = fields.Char(string=u"单位负责人")
    manager_person_mobile = fields.Char(string=u"联系方式")

    parent_id = fields.Many2one('tyibs.base.qs.company', string=u'上级质监', index=True)
    child_ids = fields.One2many('tyibs.base.qs.company', 'parent_id', string=u'下级质监')
    manager_id = fields.Many2one('tyibs.base.qs.company.employee', string=u'负责人', track_visibility='onchange')

    employee_count = fields.Integer(string=u"组员数", compute="_compute_count", store=True)
    child_ids_count = fields.Integer(string=u"直系组数", compute="_compute_count", store=True)

    employee_ids = fields.One2many('tyibs.base.qs.company.employee', 'enterprise_id', string=u'单位人员')

    # 地址信息
    province_id = fields.Many2one('tyibs.base.province', string=u'所属省份', required=True, default=lambda self:self.env["tyibs.base.province"].search([('is_default','=',True)],limit=1).id or False)
    city_id = fields.Many2one('tyibs.base.province.city', string=u'所属城市', domain="[('province_id', '=', province_id)]", required=True, default=lambda self:self.env["tyibs.base.province.city"].search([('is_default','=',True)],limit=1).id or False)
    area_id = fields.Many2one('tyibs.base.province.city.area', string=u'所属区', domain="[('city_id', '=', city_id)]")
    town_id = fields.Many2one('tyibs.base.province.city.area.town', string=u'行政区', domain="[('area_id', '=', area_id)]")
    address = fields.Char(string=u"详细地址")
    ln = fields.Float(string=u"地点经度", digits=(32, 6))
    la = fields.Float(string=u"地点纬度", digits=(32, 6))

    @api.multi
    def name_get(self):
        result = []
        for record in self:
            name = record.name
            if record.parent_id:
                name = "%s / %s" % (record.parent_id.name_get()[0][1], name)
            result.append((record.id, name))
        return result

    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError(_('错误!您不能循环创建质监局!'))

    @api.model
    def create(self, values):
        record = super(QSCompany, self).create(values)
        level = "1"
        if not record.parent_id:
            level = "1"
        else:
            if record.parent_id.parent_id:
                level = "3"
            else:
                level = "2"
        record.write({'level': level})
        return record

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        user = self.env.user
        if user.qs_level and user.qs_level != '1':
            args.append(('id', '=', user.qs_company_id.id))
        return super(QSCompany, self).search(args, offset, limit, order, count)
    


class QSEmployee(models.Model):
    """
    质监单位员工信息
    """
    _name = "tyibs.base.qs.company.employee"
    _description = u"员工信息"
    _order = 'name'

    @api.model
    def _search_enterprise_id(self):
        if self.env.user.qs_company_id:
            return ['|', ('id', '=', self.env.user.qs_company_id.id),
                    ('parent_id', '=', self.env.user.qs_company_id.id)]
        return []

    # 关联的用户
    res_user_id = fields.Many2one("res.users", string=u"关联的用户")
    user_login = fields.Char(related="res_user_id.login", readonly=True, string=u"登录账号", store=True)
    name = fields.Char(string=u"员工名称", required=True, index=True)
    code = fields.Char(string=u"员工编号")
    mobile = fields.Char(string=u'手机号', required=True)

    phone = fields.Char(u'座机电话')
    certificate = fields.Char(string=u'监察证号')
    email = fields.Char(string=u'邮箱')
    position = fields.Selection(QS_POSITION, string=u"职位")
    birthday = fields.Date(u'出生日期')
    family_phone = fields.Char(u'家庭电话')

    gender = fields.Selection([
        ('male', u'男性'),
        ('female', u'女性'),
        ('other', u'其他')
    ], string=u"性别")
    marital = fields.Selection([
        ('single', u'单身'),
        ('married', u'已婚'),
        ('widower', u'丧偶'),
        ('divorced', u'离异')
    ], string='婚姻状态')

    enterprise_id = fields.Many2one("tyibs.base.qs.company", string=u"所属单位", required=True, domain=_search_enterprise_id, default=lambda self: self.env.user.qs_company_id.id)
    has_dimission = fields.Boolean(u"是否离职", default=False)
    image = fields.Binary(u"照片", attachment=True)
    image_medium = fields.Binary(u"中等大小照片", attachment=True)
    image_small = fields.Binary(u"小尺寸照片", attachment=True)
    notes = fields.Text('备注')

    @api.multi
    def write(self, vals):
        # if vals.get('enterprise_id', False):
        #     raise ValidationError(u"不可以更改员工所在的质监单位!")
        tools.image_resize_images(vals)
        result = super(QSEmployee, self).write(vals)
        has_dimission = vals.get("has_dimission", "")
        # 如果员工离职，将其关联的用户设置为无效
        if has_dimission == False:
            self.res_user_id.sudo().write({'active': True})
        elif has_dimission == True:
            self.res_user_id.sudo().write({'active': False})
        return result

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        user = self.env.user
        if user.qs_level and user.qs_level != '1':
            args.append(('enterprise_id', '=', user.qs_company_id.id))
        return super(QSEmployee, self).search(args, offset, limit, order, count)


class UseCompany(models.Model):
    """
    使用单位
    """
    _name = 'tyibs.base.lift.use.company'

    name = fields.Char(string=u'单位名称', required=True)
    phonetic = fields.Char(string=u'拼音')
    phonetic_short = fields.Char(string=u'拼音简写')

    province_id = fields.Many2one('tyibs.base.province', string=u'所属省份', required=True, default=lambda self:self.env["tyibs.base.province"].search([('is_default','=',True)],limit=1).id or False)
    city_id = fields.Many2one('tyibs.base.province.city', string=u'所属城市', domain="[('province_id', '=', province_id)]",
                              required=True, default=lambda self:self.env["tyibs.base.province.city"].search([('is_default','=',True)],limit=1).id or False)
    area_id = fields.Many2one('tyibs.base.province.city.area', string=u'所属区', domain="[('city_id', '=', city_id)]")
    address_detail = fields.Char(string=u'详细地址')
    postcode = fields.Char(string=u'邮政编码')
    ln = fields.Float(string=u"地点经度", digits=(32, 6))
    la = fields.Float(string=u"地点纬度", digits=(32, 6))

    trust_code = fields.Char(string=u'社会统一信用代码', required=False)

    # 法人
    legal_person = fields.Char(string=u"法人")
    legal_person_mobile = fields.Char(string=u"法人手机")

    # 单位负责人
    manager_person = fields.Char(string=u"单位负责人")
    manager_person_mobile = fields.Char(string=u"联系方式")

    # 救援负责人
    save_person = fields.Char(string=u"救援负责人")
    save_person_mobile = fields.Char(string=u"联系方式")

    # 联系人
    linkman = fields.Char(string=u'联系人')
    linkman_tel = fields.Char(string=u'联系电话', size=15)
    linkman_phone = fields.Char(string=u'手机号码')
    linkman_email = fields.Char(string=u'电子邮箱')

    lift_count = fields.Integer(string=u"电梯数量")

    res_user_id = fields.Many2one("res.users", string=u"关联用户")
    user_login = fields.Char(related="res_user_id.login", readonly=True, string=u"登录账号", store=True)

    salvager_ids = fields.One2many("tyibs.base.lift.use.company.salvager", "enterprise_id", string=u"电梯管理人员")
    lift_ids = fields.One2many("tyibs.base.lift", "use_company_id", string=u"电梯资料")

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_scope", False) == "all":
            return super(UseCompany, self).sudo().search(args, offset, limit, order, count)
        elif context.get("search_scope", False) == "qs_area":
            args.append(("area_id", "=", self.env.user.qs_company_id.area_id.id))
        return super(UseCompany, self).search(args, offset, limit, order, count)

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):
        context = self._context or {}
        if context.get("search_scope", False) == "all":
            return self.sudo()._name_search(name, args, operator, limit=limit)
        return self._name_search(name, args, operator, limit=limit)


class UseCompanySalvager(models.Model):
    """
    使用单位救援资料
    """
    _name = "tyibs.base.lift.use.company.salvager"

    enterprise_id = fields.Many2one("tyibs.base.lift.use.company", string=u"使用单位", default=lambda self: self.env.user.use_company_id.id, required=True)
    # 联系信息
    role = fields.Selection(USE_COMPANY_SALVAGER_ROLES, string=u"角色", required=True)
    name = fields.Char(string=u"联系人", required=True)
    phone = fields.Char(string=u"固定电话")
    mobile = fields.Char(string=u"手机号码", required=True)


class MaintenanceCompany(models.Model):
    """
    维保单位
    """
    _name = "tyibs.base.maintenance.company"

    name = fields.Char(string=u"单位名称", required=True, index=True, search=True)
    trust_code = fields.Char(string=u'社会统一信用代码', required=False)
    maintenance_star = fields.Selection(AVILABLE_MAINTENNANCE_STARS, string=u"维保星级", index=True)
    is_salvager_unit = fields.Boolean(u"是否二级救援单位", default=False)
    local_or_remote = fields.Selection([('local', '本地'), ('remote', '异地')], u"异地/本地")

    # 法人
    legal_person = fields.Char(string=u"法人(负责人)")
    legal_person_mobile = fields.Char(string=u"法人(负责人)手机")
    legal_identity_card = fields.Char(string=u"法人(负责人)身份证")

    # 单位负责人
    manager_person = fields.Char(string=u"单位负责人")
    manager_person_mobile = fields.Char(string=u"联系方式")

    # 联系信息
    contact = fields.Char(string=u"联系人")
    phone = fields.Char(string=u"固定电话")
    mobile = fields.Char(string=u"手机号码")
    email = fields.Char(string=u"电子邮件")

    # 维保、救援
    maintenance_man = fields.Char(string=u"维保负责人")
    maintenance_man_mobile = fields.Char(string=u"维保负责人手机")
    save_man = fields.Char(string=u"应急救援负责人")
    save_man_mobile = fields.Char(string=u"应急救援负责人手机")

    # 地址信息
    province_id = fields.Many2one('tyibs.base.province', string=u'所属省份', required=True)
    city_id = fields.Many2one('tyibs.base.province.city', string=u'所属城市', domain="[('province_id', '=', province_id)]",
                              required=True)
    # 导入数据时有些地方没有
    area_id = fields.Many2one('tyibs.base.province.city.area', string=u'所属区', domain="[('city_id', '=', city_id)]")
    address = fields.Char(string=u"详细地址")
    ln = fields.Float(string=u"地点经度", digits=(32, 6))
    la = fields.Float(string=u"地点纬度", digits=(32, 6))

    # 特种设备许可证信息
    special_card_num = fields.Char(string=u"许可证编号" )
    special_card_period = fields.Date(string=u"许可证有效期" )
    special_card_approver = fields.Char(string=u"许可证颁发单位" )
    special_card_att_id = fields.Binary(string=u"许可证附件", attachment=True, public=True)
    # 营业执照附件
    attachment_ids = fields.Many2many("ir.attachment", string="营业执照",
                                      domain="[('res_model','=','tyibs.base.maintenance.company'), ('res_id','=',id)]")

    department_ids = fields.One2many("tyibs.base.maintenance.company.department", "enterprise_id", string=u"分组")
    employee_ids = fields.One2many("tyibs.base.maintenance.company.employee", "enterprise_id", string=u"员工")
    site_ids = fields.One2many("tyibs.base.maintenance.company.site", "enterprise_id", string=u"二级驻点资料")
    salvager_ids = fields.One2many("tyibs.base.maintenance.company.salvager", "enterprise_id", string=u"救援资料")

    filing_date = fields.Date(string=u"备案日期")
    next_filing_date = fields.Date(string=u"下次备案日期")

    rescue_vehicle_ids = fields.One2many("tyibs.base.maintenance.rescue.vehicle", "enterprise_id", string=u"救援车辆")
    company_telephone = fields.Char(string=u"公司固话")
    company_email = fields.Char(string=u"公司邮箱")

    res_user_id = fields.Many2one("res.users", string=u"关联的用户")
    user_login = fields.Char(related="res_user_id.login", readonly=True, string=u"登录账号", store=True)
    lift_ids = fields.One2many("tyibs.base.lift", "maintenance_company_id", string=u"电梯资料")

    @api.model
    def create(self, vals):
        record = super(MaintenanceCompany, self).create(vals)
        site_vals = {   
                        "name": vals.get("name"),
                        "enterprise_id": record.id,
                        "province_id": vals.get("province_id"),
                        "city_id": vals.get("city_id"),
                        "address": vals.get("address"),
                        "ln": vals.get("ln"),
                        "la": vals.get("la")
                     }
        if vals.get("area_id", None):
            site_vals["area_id"] = vals.get("area_id")
        site = self.env["tyibs.base.maintenance.company.site"].create(site_vals)
        if vals.get("maintenance_man", False) and vals.get("maintenance_man_mobile", False):
            salvager_vals = {
                "enterprise_id": record.id,
                "site_id": site.id,
                "role": "second_salvager",
                "name": vals.get("maintenance_man"),
                "mobile": vals.get("maintenance_man_mobile")
            }
            self.env["tyibs.base.maintenance.company.salvager"].create(salvager_vals)
        if vals.get("save_man", False) and vals.get("save_man_mobile", False):
            salvager_vals = {
                "enterprise_id": record.id,
                "site_id": site.id,
                "role": "first_salvager",
                "name": vals.get("save_man"),
                "mobile": vals.get("save_man_mobile")
            }
            self.env["tyibs.base.maintenance.company.salvager"].create(salvager_vals)
        if vals.get("contact", False) and vals.get("mobile", False):
            salvager_vals = {
                "enterprise_id": record.id,
                "site_id": site.id,
                "role": "head_of_unit",
                "name": vals.get("contact"),
                "mobile": vals.get("mobile")
            }
            self.env["tyibs.base.maintenance.company.salvager"].create(salvager_vals)

        return record

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "main_menu":
            args.append(('id', '=', self.env.user.main_company_id.id))
        return super(MaintenanceCompany, self).search(args, offset, limit, order, count)

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        context = self._context or {}
        res = super(MaintenanceCompany, self).fields_view_get(view_id=view_id, view_type=view_type,
                                                toolbar=toolbar, submenu=False)
        if context.get("search_from", False) == "main_menu":
            if res['type'] == "form":
                doc = etree.XML(res['arch'])
                map(lambda item: item.set("modifiers", '{"readonly": true}'),
                    doc.xpath("//field[@class='readonly_for_main']"))
                res['arch'] = etree.tostring(doc)
        return res

    @api.multi
    def write(self, vals):
        if vals.get("special_card_att_id", False):
            maintenance_group_id = self.env.ref("lift_base.group_lift_main_company_employee").id
            if maintenance_group_id in self.env.user.groups_id.ids:
                raise ValidationError(u"维保单位不能更改特种设备许可证书附件。")
        return super(MaintenanceCompany, self).write(vals)


class MaintenanceDepartment(models.Model):
    """
    维保单位组
    """
    _name = "tyibs.base.maintenance.company.department"
    _description = u"维保单位组"
    _order = "name"

    name = fields.Char(u'名称', required=True)
    enterprise_id = fields.Many2one('tyibs.base.maintenance.company', string=u'所属维保公司', required=True, index=True, default=lambda self: self.env.user.main_company_id.id)
    parent_id = fields.Many2one('tyibs.base.maintenance.company.department', string=u'上级组',
                                domain="[('enterprise_id','=',enterprise_id)]", index=True)
    child_ids = fields.One2many('tyibs.base.maintenance.company.department', 'parent_id', string=u'下级部门')
    manager_id = fields.Many2one('tyibs.base.maintenance.company.employee', string=u'负责人', track_visibility='onchange', domain="[('enterprise_id','=',enterprise_id)]")
    employee_ids = fields.One2many('tyibs.base.maintenance.company.employee', 'department_id', string=u'组员')
    remark = fields.Text(u'备注')

    employee_count = fields.Integer(string=u"组员数", compute="_compute_count", store=True)
    child_ids_count = fields.Integer(string=u"直系组数", compute="_compute_count", store=True)

    @api.depends("employee_ids", "child_ids")
    def _compute_count(self):
        for item in self:
            item.employee_count = len(item.employee_ids)
            item.child_ids_count = len(item.child_ids)

    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError(_('错误!您不能循环创建组!'))

    @api.multi
    def name_get(self):
        result = []
        for record in self:
            name = record.name
            if record.parent_id:
                name = "%s / %s" % (record.parent_id.name_get()[0][1], name)
            result.append((record.id, name))
        return result

    @api.multi
    def unlink(self):
        for item in self:
            if item.employee_count > 0 or item.child_ids_count > 0:
                raise ValidationError(u"部门下有子部门或组员，不能删除")
        super(MaintenanceDepartment, self).unlink()


class MaintenanceEmployee(models.Model):
    """
    维保单位员工信息
    """
    _name = "tyibs.base.maintenance.company.employee"
    _description = u"员工信息"
    _order = 'name'
    name = fields.Char(string=u"员工名称", required=True, index=True)
    code = fields.Char(string=u"员工编号")
    mobile = fields.Char(string=u'手机号', required=True)
    phone = fields.Char(u'座机电话')
    identification_id = fields.Char(string=u'身份证号', required=True)
    position = fields.Selection([("main_emp","维保人员"),("clerk","文员"),("other","其它")],string=u"职务")
    email = fields.Char(string=u'邮箱')
    birthday = fields.Date(u'出生日期')
    contract_date = fields.Date(u"合同到期日期")
    # 定期计算
    contract_over_time = fields.Boolean(u"合同已到期", default=False)
    family_phone = fields.Char(u'家庭电话')

    gender = fields.Selection([
        ('male', u'男性'),
        ('female', u'女性'),
        ('other', u'其他')
    ], string=u"性别")
    marital = fields.Selection([
        ('single', u'单身'),
        ('married', u'已婚'),
        ('widower', u'丧偶'),
        ('divorced', u'离异')
    ], string='婚姻状态')

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string=u"所属单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    department_id = fields.Many2one('tyibs.base.maintenance.company.department', string=u'人员分组',domain="[('enterprise_id','=',enterprise_id)]")
    has_dimission = fields.Boolean(u"是否离职", default=False)
    image = fields.Binary(u"照片", attachment=True)
    image_medium = fields.Binary(u"中等大小照片", attachment=True)
    image_small = fields.Binary(u"小尺寸照片", attachment=True)
    certificate_ids = fields.One2many("tyibs.base.maintenance.company.employee.certificate", "employee_id", string=u"员工证书")
    certificate_valid = fields.Boolean(string=u"证书有效", store=True, compute="_compute_certificate_valid")
    res_user_id = fields.Many2one("res.users", string=u"关联的用户")
    user_login = fields.Char(related="res_user_id.login", readonly=True, string=u"登录账号", store=True)
    notes = fields.Text('备注')

    @api.multi
    @api.depends("certificate_ids")
    def _compute_certificate_valid(self):
        for item in self:
            valid_cer = item.certificate_ids.filtered(lambda cer: not cer.has_over_time)
            item.certificate_valid = True if valid_cer else False

    def check_employee_exist(self, identification_id):
        if identification_id:
            employee = self.sudo().search([('identification_id', '=', identification_id), ('has_dimission', '=', False)],
                                          limit=1)
            if employee:
                raise Warning(u"身份证号为{}的员工已在其它维保公司任职。".format(identification_id))

    @api.model
    def create(self, vals):
        identification_id = vals.get("identification_id")
        self.check_employee_exist(identification_id)
        return super(MaintenanceEmployee, self).create(vals)

    @api.multi
    def write(self, vals):
        # 如果改了身份证，判断身份证是否重复
        self.check_employee_exist(vals.get('identification_id', False))
        if vals.get('enterprise_id', False):
            raise ValidationError(u"不可以更改员工所在的企业!")
        has_dimission = vals.get("has_dimission", "")
        # 如果员工离职，将其关联的用户设置为无效
        if has_dimission == False:
            # 如果员工由离职改为在职，判断是否有重复的在职员工
            self.check_employee_exist(self.identification_id)
            self.res_user_id.sudo().write({'active': True})
        elif has_dimission == True and self.res_user_id:
            self.res_user_id.sudo().write({'active': False})
        tools.image_resize_images(vals)
        return super(MaintenanceEmployee, self).write(vals)

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        if context.get("search_from", False) == "maintenance":
            args.append(('enterprise_id', '=', self.env.user.main_company_id.id))
        return super(MaintenanceEmployee, self).search(args, offset, limit, order, count)

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        context = self._context or {}
        res = super(MaintenanceEmployee, self).fields_view_get(view_id=view_id, view_type=view_type,
                                                         toolbar=toolbar, submenu=False)
        if (res['type'] == "form" or res['type'] == 'tree') and context.get("readonly", False):
            doc = etree.XML(res['arch'])
            form_xpath = doc.xpath("//{}".format(res['type']))[0]
            form_xpath.set("create", "false")
            form_xpath.set("edit", "false")
            form_xpath.set("delete", "false")
            res['arch'] = etree.tostring(doc)
        return res


class MaintenanceEmployeeCertificate(models.Model):
    """
    维保单位员工证书
    """
    _name = "tyibs.base.maintenance.company.employee.certificate"
    _description = u"员工证书"
    _rec_name = "code"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string=u"所属单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    employee_id = fields.Many2one("tyibs.base.maintenance.company.employee", string=u"所属员工", required=True, domain="[('enterprise_id', '=', enterprise_id)]")
    card_category_id = fields.Many2one("tyibs.base.maintenance.card.category", string=u"证书类型", required=True)
    code = fields.Char(string=u"证书编号", required=True)
    period = fields.Date(string=u"过期时间")
    # 定期计算
    has_over_time = fields.Boolean(u"证书已到期", default=False)
    card_attach_id = fields.Binary(string=u"缩略图", attachment=True, public=True)

    @api.onchange("period")
    def _compute_has_over_time(self):
        self.has_over_time = self.period < datetime.datetime.now().strftime("%Y-%m-%d")


class MaintenanceCompanySite(models.Model):
    """
    维保单位二级驻点
    """
    _name = "tyibs.base.maintenance.company.site"

    name = fields.Char(string=u"驻点名称", required=True, index=True, search=True)
    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string=u"维保公司", required=True, default=lambda self: self.env.user.main_company_id.id)
    # 联系信息
    manager_id = fields.Many2one("tyibs.base.maintenance.company.employee", string=u"负责人", domain="[('enterprise_id','=',enterprise_id)]")
    manager_name = fields.Char(related="manager_id.name", store=True, string=u"负责人")
    manager_mobile = fields.Char(related="manager_id.mobile", store=True)
    manager_phone = fields.Char(related="manager_id.phone", store=True)
    salvager_ids = fields.One2many("tyibs.base.maintenance.company.salvager", "site_id", string=u"救援人员")

    # 地址信息
    province_id = fields.Many2one('tyibs.base.province', string=u'所属省份', required=True, default=lambda self:self.env["tyibs.base.province"].search([('is_default','=',True)],limit=1).id or False)
    city_id = fields.Many2one('tyibs.base.province.city', string=u'所属城市', domain="[('province_id', '=', province_id)]", required=True, default=lambda self:self.env["tyibs.base.province.city"].search([('is_default','=',True)],limit=1).id or False)
    area_id = fields.Many2one('tyibs.base.province.city.area', string=u'所属区', domain="[('city_id', '=', city_id)]")
    address = fields.Char(string=u"详细地址")

    ln = fields.Float(string=u"地点经度", digits=(32, 6))
    la = fields.Float(string=u"地点纬度", digits=(32, 6))

    @api.onchange("enterprise_id")
    def check_address_change(self):
        if self.enterprise_id.province_id:
            self.province_id = self.enterprise_id.province_id

        if self.enterprise_id.city_id:
            self.city_id = self.enterprise_id.city_id

        if self.enterprise_id.area_id:
            self.area_id = self.enterprise_id.area_id


class MaintentanceCompanySalvager(models.Model):
    """
    救援资料
    """
    _name = "tyibs.base.maintenance.company.salvager"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string=u"维保公司", required=True, default=lambda self: self.env.user.main_company_id.id)
    # 联系信息
    site_id = fields.Many2one("tyibs.base.maintenance.company.site", string=u"站点")
    role = fields.Selection(MAINTENANCE_SALVAGER_ROLES, string=u"角色", required=True)
    name = fields.Char(string=u"联系人", required=True)
    phone = fields.Char(string=u"固定电话")
    mobile = fields.Char(string=u"手机号码", required=True)


class RescueVehicle(models.Model):
    """
    救援车辆
    """

    _name = "tyibs.base.maintenance.rescue.vehicle"
    _rec_name = "code"

    enterprise_id = fields.Many2one("tyibs.base.maintenance.company", string=u"所属维保单位", required=True, default=lambda self: self.env.user.main_company_id.id)
    code = fields.Char(string=u"车牌号", required=True)
    GPS_code = fields.Char(string=u"GPS编码", required=True)
    GPS_mobile = fields.Char(string=u"GPS车载电话", required=True)
    manager = fields.Char(string=u"车辆负责人", required=True)
    manager_mobile = fields.Char(string=u"车辆负责人电话", required=True)

    _sql_constraints = [("unique_gps_code", "unique(GPS_code)", u"救援车辆GPS编码已存在！")]

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        context = self._context or {}
        res = super(RescueVehicle, self).fields_view_get(view_id=view_id, view_type=view_type,
                                                              toolbar=toolbar, submenu=False)
        if context.get("search_from", False) == "main_menu":
            if res['type'] == "form":
                doc = etree.XML(res['arch'])
                map(lambda item: item.set("modifiers", '{"readonly": true}'),
                    doc.xpath("//field[@class='readonly_for_main']"))
                res['arch'] = etree.tostring(doc)
        return res


class DisposeCenter(models.Model):
    """
    处置中心
    """

    _name = 'tyibs.base.lift.dispose.center'

    name = fields.Char(string=u"名称", required=True)
    province_id = fields.Many2one("tyibs.base.province", string=u"省", required=True)
    city_id = fields.Many2one("tyibs.base.province.city", string=u"市", domain="[('province_id', '=', province_id)]", required=True)
    area_id = fields.Many2one("tyibs.base.province.city.area", string=u"区/县", domain="[('city_id', '=', city_id)]", required=True)
    address = fields.Char(string=u"地址")
    linkman = fields.Char(string=u"联系人")
    linkman_tel = fields.Char(string=u"联系电话")
    remark = fields.Text(string=u"备注")
    res_user_id = fields.Many2one("res.users", string=u"关联的用户")
    customer_service_ids = fields.One2many("tyibs.base.lift.dispose.center.customer.service", "dispose_center_id", string=u"客服人员")


class CustomerService(models.Model):
    """
    客服人员
    """

    _name = "tyibs.base.lift.dispose.center.customer.service"

    name = fields.Char(string=u"姓名", required=True)
    code = fields.Char(string=u"客服编号", required=True)
    mobile = fields.Char(string=u"电话", required=True)
    email = fields.Char(string=u"电子邮件")
    position = fields.Selection([('normal', u'普通员工'), ('manager', u'主管')], string=u"职位")
    working_status = fields.Selection([('working', u'在职'), ('leave', u'请假'), ('resign', u'辞职')], string=u"在职状态", default="working")
    dispose_center_id = fields.Many2one("tyibs.base.lift.dispose.center", string=u"处置中心", required=True)
    res_user_id = fields.Many2one("res.users", string=u"关联的用户")
    remark = fields.Text(string=u"备注")

    _sql_constraints = [("unique_code", "unique(code)", u"客服编号已存在！")]

    @api.multi
    def write(self, vals):
        # if vals.get('dispose_center_id', False):
        #     raise ValidationError(u"不可以更改员工所在的处置中心!")
        tools.image_resize_images(vals)
        result = super(CustomerService, self).write(vals)
        working_status = vals.get("working_status", False)
        # 如果员工离职，将其关联的用户设置为无效
        if working_status == "working" or working_status == "leave":
            self.res_user_id.sudo().write({'active': True})
        elif working_status == "resign":
            self.res_user_id.sudo().write({'active': False})
        return result
